package dao

import javax.inject.Inject
import models.Tables._
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import slick.jdbc.JdbcProfile

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

/**
 * Created by yz on 2018/5/29
 */
class DataDao @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) extends
  HasDatabaseConfigProvider[JdbcProfile] {

  import profile.api._

  def insertOrUpdates(rows: Seq[DataRow]) = {
    val action = {
      val delete = Data.delete
      val insertAll = Data ++= rows
      delete.flatMap(_ => insertAll)
    }.transactionally
    db.run(action).map(_ => ())
  }

  def selectAll = db.run(Data.result)

  def selectAll(barcode: String) = db.run(Data.filter(_.barcode === barcode).result)

  def selectAllBySampleName(sampleName: String) = db.run(Data.
    filter(_.sampleName === sampleName).result)

  def selectAllByRefGene(refGene: String) = db.run(Data.
    filter(_.refGene === refGene).result)

  def selectAll(barcode: String, refGene: String) = db.run(Data.
    filter(_.barcode === barcode).filter(_.refGene === refGene).result)

  def selectAllRefGene(barcode: String) = db.run(Data.filter(_.barcode === barcode).
    map(_.refGene).distinct.result)

  def selectSingleColumn(columnName: String) = db.run(Data.map { x =>
    columnName match {
      case "barcode" => x.barcode
      case "refGene" => x.refGene
      case "sampleName" => x.sampleName
    }
  }.distinct.result)

  def select(barcode: String) = db.run(Data.filter(_.barcode === barcode).result.head)

  def deleteAll(ids: Seq[Int]) = db.run(Data.filter(_.id.inSetBind(ids)).delete).map(_ => ())

  def delete(id: Int) = db.run(Data.filter(_.id === id).delete).map(_ => ())


}
